package com.rzjm.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.dao.DeviceWaterCardMapper;
import com.rzjm.api.dao.DeviceWaterOrderMapper;
import com.rzjm.api.dao.DeviceWaterRecordMapper;
import com.rzjm.api.entity.*;
import com.rzjm.api.exception.TransactionalException;
import com.rzjm.api.netty.water.entity.ReceiveData;
import com.rzjm.api.service.IDeviceWaterOrderService;
import com.rzjm.api.service.PlatformPayService;
import com.rzjm.api.util.MathUtil;
import com.rzjm.api.util.OrderUtil;
import com.rzjm.api.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.WeakHashMap;

/**
 * 充电订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-07
 */
@Service
public class DeviceWaterOrderServiceImpl extends BaseServiceImpl<DeviceWaterOrderMapper, DeviceWaterOrder> implements IDeviceWaterOrderService {

    @Resource
    private DeviceWaterOrderMapper waterOrderMapper;
    @Resource
    private DeviceWaterCardMapper waterCardMapper;
    @Resource
    private DeviceWaterRecordMapper waterRecordMapper;

    @Resource
    private PlatformPayService platformPayService;

    @Override
    public DeviceWaterOrder addOrderByCard(DeviceWater device, DeviceWaterCard waterCard) {

        QueryWrapper<DeviceWaterOrder> qw = new QueryWrapper<>();
        qw.eq("device_id", device.getId());
        //订单状态 0 - 未支付   1 - 支付中  2 - 已支付  3 - 充电中  4 - 已发起退款  5 - 退款完成  6 - 退款失败  7 - 订单已完成（结束） 8 -  订单取消
        qw.in("status", 0 ,1);
        qw.orderByDesc("create_time");
        qw.last("limit 1");
        DeviceWaterOrder order = waterOrderMapper.selectOne(qw);
        if(order != null){
            return order;
        }
        order = new DeviceWaterOrder();
//        PlatformPay platformPay = platformPayService.findById(device.getPayPlatformId());
        String orderNo = OrderUtil.getWaterOrderPayNo();
        order.setOrderNo(orderNo);
        order.setOutTradeNo(orderNo);
        order.setDeviceId(device.getId());
        order.setCardId(waterCard.getId());
        order.setCardNum(waterCard.getCardNum());
        order.setPayType(1);//水卡支付
        /**
         * 订单状态 0 - 未支付   1 - 支付中  2 - 已支付  3 - 充电中  4 - 已发起退款  5 - 退款完成  6 - 退款失败  7 - 订单已完成（结束） 8 -  订单取消
         */
        order.setStatus(0);
        order.setCreateTime(new Date());
        order.setIsDel(0);
        /**
         * 订单类型  0 - 水卡打水订单  1 - 扫码打水订单
         */
        order.setOrderType(0);

        order.setTotalPrice(device.getSinglePrice());
        order.setFee(new BigDecimal(0));
        order.setPayPrice(new BigDecimal(0));
        order.setUseVolume(new BigDecimal(0));
        order.setUsePrice(new BigDecimal(0));
        order.setRefundStatus(0);
        int ret = waterOrderMapper.insert(order);
        if(ret > 0){
            return order;
        }
        return null;
    }

    @Override
    @Transactional
    public int overOrderByCard(DeviceWater device, DeviceWaterOrder waterOrder, ReceiveData receiveData) {
        int ret = 0;
        try{
            String useMoney = receiveData.getV2();
            String useVolume = receiveData.getV3();
            System.out.println("出水量：" + useVolume + "毫升");
            System.out.println("上传金额：" + useMoney);

            /**
             * 订单状态 0 - 未支付   1 - 支付中  2 - 已支付  3 - 充电中  4 - 已发起退款  5 - 退款完成  6 - 退款失败  7 - 订单已完成（结束） 8 -  订单取消
             */
            double useMoneyDb = MathUtil.getDoubleUp(Double.parseDouble(useMoney) / 100);
            System.out.println("转换后的金额：" + useMoneyDb);
            if(useMoneyDb > device.getSinglePrice().doubleValue()){// 最多不能超过单价 3元
                useMoneyDb = device.getSinglePrice().doubleValue();
            }
            System.out.println("实际扣除金额：" + useMoneyDb);
            waterOrder.setStatus(7);
            waterOrder.setOverTime(new Date());
            waterOrder.setUsePrice(new BigDecimal(useMoneyDb));
            waterOrder.setUseVolume(new BigDecimal(useVolume));
            waterOrder.setDeviceId(device.getId());
            ret = waterOrderMapper.updateById(waterOrder);
            if(ret <= 0){
                throw new TransactionalException("waterOrderMapper updateById error");
            }

            DeviceWaterRecord waterRecord = new DeviceWaterRecord();
            waterRecord.setDeviceId(waterOrder.getDeviceId());
            DeviceWaterCard waterCard = waterCardMapper.selectById(waterOrder.getCardId());
            if(waterCard != null){
//                double useMoneyDb = MathUtil.getDoubleUp(Double.parseDouble(useMoney) / 100);
                double leftMoney = waterCard.getAccountMoney().doubleValue();
                System.out.println("消费之前价格：" + leftMoney);
                leftMoney = leftMoney- useMoneyDb;
                System.out.println("消费之后价格：" + leftMoney);
                waterCard.setAccountMoney(new BigDecimal(leftMoney));
                ret = waterCardMapper.updateById(waterCard);
                if(ret <= 0){
                    throw new TransactionalException("waterCardMapper updateById error");
                }
                waterRecord.setCardId(waterCard.getId());
            }



            waterRecord.setCreateTime(new Date());
            waterRecord.setPayPrice(new BigDecimal(StringUtil.centToYuan(useMoney)));
            waterRecord.setUseVolume(new BigDecimal(StringUtil.centToYuan(useVolume)));
            ret = waterRecordMapper.insert(waterRecord);
            if(ret <= 0){
                throw new TransactionalException("waterRecordMapper insert error");
            }

        }catch (Exception e){
            throw new TransactionalException("overOrderByCard system error");
        }
        return ret;
    }
}
